import _ from "lodash";
import Order from "./Order.js";

export default class ShoppingCart {
    constructor(customer, products) {
        this.customer = customer;
        this.products = products;
    };

    addProduct = (product) => {
        this.products.push(product);
    };

    removeProduct = (product) => {
        _.remove(this.products, product);
    };

    checkout = () => {
        let totalPrice = 0;
        let loyaltyPointsEarned = 0;

        let log = new Map();
        this.products.forEach(product => {
            log.set(product.code, 0)
        })

        this.products.forEach(product => {
            let discount = 0;
            
            if (product.code.startsWith("BULK_BUY_2_GET_1")){
                log.set(product.code, log.get(product.code)+1)
                if (log.get(product.code) === 3){
                    log.set(product.code, 0);
                    discount = product.price
                }
            } else if (product.code.startsWith("DIS_10")) {
                discount = product.price * 0.1;
                loyaltyPointsEarned += product.price / 10;
            } else if (product.code.startsWith("DIS_15")) {
                discount = product.price * 0.15;
                loyaltyPointsEarned += product.price / 15;
            } else if (product.code.startsWith("DIS_20")) {
                discount = product.price * 0.20;
                loyaltyPointsEarned += product.price / 20;
            } else {
                loyaltyPointsEarned += product.price / 5;
            }

            totalPrice += product.price - discount;
        })
        totalPrice = totalPrice > 500 ? totalPrice*0.95 : totalPrice
        return new Order(totalPrice, loyaltyPointsEarned);
    };

    displaySummary = () => {
        return "Customer: " + this.customer.name + "\n" +
            "Bought:  \n" + this.products.map(p => "- " + p.name + ", " + p.price).join('\n');
    }
};
